<template>

<div class="config-tabs-pane">
    <div class="config-tab-heads">
      <div :class="activeTab=='public'?'config-tab-head selected' : 'config-tab-head'" @click.stop="handleClickTabs('public')">通用配置</div> 
      <div :class="activeTab=='private'?'config-tab-head selected' : 'config-tab-head'" @click.stop="handleClickTabs('private')">自定义配置</div>
	  <div :class="activeTab=='event'?'config-tab-head selected' : 'config-tab-head'" @click.stop="handleClickTabs('event')">事件配置</div>
	  <div :class="activeTab=='data-src'?'config-tab-head selected' : 'config-tab-head'" @click.stop="handleClickTabs('data-src')">数据源配置</div>
    </div>
    <div class="config-tab-body">
      <div class="public-config" v-show="activeTab=='public'">
        <el-form  @submit.prevent label-position="top">
          <el-form-item label="组件名称">
              <el-input v-model="props.component.title" />
          </el-form-item>

          <el-row :gutter="8" style="margin-bottom: 12px;">
            <el-col :span="12">
              <el-form-item label="宽度">
                <el-input-number v-model="props.component.width" :min="0" :max="90000" controls-position="right"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="高度">
                <el-input-number v-model="props.component.height" :min="0" :max="90000" controls-position="right"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="8" style="margin-bottom: 12px;">
            <el-col :span="12">
              <el-form-item label="位置X">
                <el-input-number v-model="props.component.x" :min="0" :max="90000" controls-position="right"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置Y">
                <el-input-number v-model="props.component.y" :min="0" :max="90000" controls-position="right"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="背景颜色">
              <el-color-picker v-model="props.component.bgColor"  show-alpha />
          </el-form-item>
		  
		  <el-form-item label="旋转">
				<el-slider v-model="props.component.rotate" :min="0" :max="360" show-input />
		  </el-form-item>
		  
		  <el-form-item label="进场动画">
			    <el-select v-model="props.component.enterAnimation" placeholder="请选择进场动画" >
			      <el-option label="左侧淡入" value="animate__fadeInLeftBig"/>
				  <el-option label="右侧淡入" value="animate__fadeInRightBig"/>
				  <el-option label="向上淡入" value="animate__fadeInDownBig"/>
			    </el-select>
		  </el-form-item>
		  
		  <el-form-item label="离场动画">
				<el-select v-model="props.component.leaveAnimation" placeholder="请选择离场动画" >
				  <el-option label="左侧淡出" value="animate__fadeOutLeftBig"/>
				  <el-option label="右侧淡出" value="animate__fadeOutRightBig"/>
				  <el-option label="向下淡出" value="animate__fadeOutDownBig"/>
				</el-select>
		  </el-form-item>
		  
		  
		  <el-form-item label="动画时间(秒)">
				<el-input-number v-model="props.component.animationDuration" :step="0.1" :min="0" :max="10" controls-position="right"/>
		  </el-form-item>
		  
        </el-form>
      </div>
      <div class="private-config" v-show="activeTab=='private'">
        <el-scrollbar height="calc(100vh - 208px)">
        <component 
          :is="resolvedComponent"
          v-if="resolvedComponent && !error"
          :id="props.component.id"
          v-bind="computedConfig"
          :key="props.component.id + '-' + (props.component.componentId || props.component.type)"
          class="rendered-component"
          @config-change="change"
          @error="handleComponentError"
        />
        
        <div v-else class="fallback-component">
          <div class="fallback-content">
            <i :class="fallbackIcon" class="fallback-icon"></i>
            <div class="fallback-text">{{ props.component.title || '未知组件配置' }}</div>
            <div class="fallback-type">{{ props.component.type }}</div>
            <div v-if="error" class="fallback-error">{{ error }}</div>
            <div v-if="loading" class="fallback-loading">加载中...</div>
            <div class="fallback-debug">
              <div>Component ID: {{ props.component.id }}</div>
              <div>Component Type: {{ props.component.type }}</div>
              <div>Component ID: {{ props.component.componentId }}</div>
              <div>Config: {{ JSON.stringify(props.component.config) }}</div>
            </div>
          </div>
        </div>
      </el-scrollbar>
      </div>
	  
	  <div class="private-config" v-show="activeTab=='event'">
		<ComponentEventPane type="component" :component="props.component" :structure="props.structure" :bindings="props.component?.bindings||[]" @bindings="handleBindings"/> 
		  
<!-- 		  <div class="event-tool-bar">
		    <el-button type="primary" :icon="Plus" text @click="openAddDialog">添加绑定</el-button>
		  </div>
		  <el-scrollbar height="calc(100vh - 208px)">
			  <div class="event-binding-list">
			    <div class="event-binding-row" v-for="bind in bindings" :key="bind.id">
			      <div class="item">
			        <span>{{ bind.name }}</span>
			      </div>
			      <div>
			        <el-button type="danger" :icon="Delete" text @click.stop="remove(bind)">移除绑定</el-button>
			      </div>
			    </div>
			  </div>
		  </el-scrollbar> -->
	  </div>
	  <div class="private-config" v-show="activeTab=='data-src'">
	  	<ComponentDataPane type="component" :component="props.component" :structure="props.structure" :bindings="props.component?.bindings||[]" @bindings="handleBindings"/>
	  </div>
    </div>
	
	
</div>
  
</template>

<script setup lang="ts">
import {
  Check,
  Delete,
  Plus,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'
import { ref, watch, computed, shallowRef, markRaw, onBeforeUnmount } from 'vue'
import { ComponentLibraryService } from '@/api/visual/componentLibraryApi'
import { axiosInstance } from '@/utils/http/index'
import { ComponentInstance } from '@/types/visual-app';
import { componentManager} from '@/components/visual/util/DynamicComponentUtil'
import ComponentEventPane from '@/components/visual/widget/ComponentEventPane.vue'
import ComponentDataPane from '@/components/visual/widget/ComponentDataPane.vue'


const BASE_API = axiosInstance.defaults.baseURL
const props = defineProps<{ component: ComponentInstance ,structure:any}>()
// 结构树属性

const activeTab=ref<string>('public');
const emit = defineEmits(['config-change'])
// 响应式数据
const resolvedComponent = shallowRef<any>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const fallbackIcon = computed(() => {
  return 'el-icon-question'
})

const computedConfig = computed(() => {
  if (!props.component.config || typeof props.component.config !== 'object') {
    props.component.config = {}
  }
  props.component.config['componentId']=props.component.componentId
  return props.component.config
})

const loadComponent = async () => {
  if (!props.component.componentId) {
    error.value = '组件类定义'
    return
  }

  loading.value = true
  error.value = null

  try {

    const cacheKey = props.component.componentId;  
    const meta = await componentManager.getComponentMeta(cacheKey, getComponentLById);

    // 处理路径，全部用相对路径 ./ 开头
    let importPath = meta.configPath || '';
    if (importPath.startsWith('/')) {
      importPath = '..' + importPath; 
    } else if (!importPath.startsWith('.')) {
      importPath = '../library/' + importPath.replace(/^[/\\]?widget[/\\]?/, '');
    }
    const asyncComponent = componentManager.getAsyncComponent(importPath);
    if (asyncComponent) {
      resolvedComponent.value = markRaw(asyncComponent)
    } else {
      error.value = `无法加载组件: ${props.component.title}`+'配置面板.'
    }
  } catch (err) {
    error.value = `加载组件配置面板失败: ${err}`
    console.error('Component loading error:', err)
  } finally {
    loading.value = false
  }
}

const getComponentLById=async ()=>{
  return await ComponentLibraryService.get(props.component.componentId);
}

watch(() => props.component.componentId, () => {
  loadComponent()
}, { immediate: true })

const handleBindings = (bindings: any[]) => {
  if (!Array.isArray(props.component.bindings)) {
    props.component['bindings'] = [...bindings];
  }else{
	  props.component.bindings = [...bindings]; 
  }
};

onBeforeUnmount(() => {
  resolvedComponent.value = null
})

//切换tab
const handleClickTabs=(tab:string)=>{
  activeTab.value=tab;
}

const change = (field:{key:string,value:Object}) => {
  if(!props.component.hasOwnProperty('config')){
    props.component['config']={};
  }
  if(props.component.config.hasOwnProperty(field.key)){
    props.component.config[field.key]=field.value;
  }else{
    props.component.config[field.key]=field.value;
  } 
}

const handleComponentError = (err: string) => {
  console.error('Component error:', err);
  error.value = err;
};

</script> 

<style scoped>

.config-tabs-pane{
  border: 0px solid var(--art-card-border);
  background-color: var(--art-main-bg-color);
  overflow: hidden;
  .config-tab-heads{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    background: linear-gradient(90deg, #5d87ffb5 0%, #1e90ff4f 100%);
    .config-tab-head{
      padding: 6px;
      color: #fffefe;
      cursor: pointer;
      border-right: 1px solid var(--art-card-border);
      font-size: 14px;
    }
    .selected{
      background: #5d87ff;
      color: #fff;
    }
  }
  .config-tab-body{
    padding: 16px;
    border: 1px solid var(--art-card-border);
  }
}


.component-panel{
  border: 0px solid var(--art-card-border);
  padding: 0px;
  background-color: var(--art-main-bg-color);
  overflow: hidden;
}

.component-title-bar {
  height: 36px;
  background: linear-gradient(90deg, #5d87ffb5 0%, #1e90ff4f 100%);
  line-height: 36px;
  border-left: 0px solid #5d87ff;
  padding-left: 16px;
  color: #fff;
  font-weight: bold;
  font-size: 16px;
  /* box-shadow: 0 2px 8px #0002; */
  letter-spacing: 1px;
  /* margin-bottom: 10px; */
  position: relative;
  z-index: 1;
}

.component-body{
  padding: 8px;
  /* box-shadow: 0 1px 8px #5d87ff; */
  border: 1px solid var(--art-card-border);
}

.attribute-class > div {
  margin-bottom: 14px;
  padding: 10px 0;
  border-bottom: 1px dashed #3a3f4b;
}

.attribute-class > div:last-child {
  border-bottom: none;
}

.attribute-class label,
.attribute-class .title {
  font-weight: 600;
  color: #fff;
  font-size: 13px;
  margin-bottom: 6px;
  display: block;
  width: 150px;
}

.attribute-class .row-item{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: flex-start;
  align-items: flex-start;
  margin-bottom: 5px;
  /* border-top: 1px solid #333333; */
  padding: 0px 8px 0px 8px;
}

.attribute-class .el-input,
.attribute-class .el-input-number,
.attribute-class .el-select,
.attribute-class .el-switch,
.attribute-class .el-date-picker {
  width: 220px;
  background: #1a1d23;
  /* border-radius: 4px; */
  color: #fff;
}

.attribute-class .el-input__inner,
.attribute-class .el-input-number__inner {
  background: #1a1d23;
  color: #fff;
  border: 1px solid #353a45;
}

.attribute-class .el-input__inner:focus,
.attribute-class .el-input-number__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px #409eff33;
}

.attribute-class .el-switch__core {
  background: #353a45;
}

.attribute-class .el-switch.is-checked .el-switch__core {
  background: #409eff;
}

.fallback-component {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border: 1px dashed #c0c4cc;
  border-radius: 4px;
  
  .fallback-content {
    text-align: center;
    color: #909399;
    
    .fallback-icon {
      font-size: 32px;
      margin-bottom: 8px;
      opacity: 0.6;
    }
    
    .fallback-text {
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 4px;
    }
    
    .fallback-type {
      font-size: 12px;
      opacity: 0.8;
    }
    
    .fallback-error {
      font-size: 12px;
      color: #f56c6c;
      margin-top: 8px;
      padding: 8px;
      background: rgba(245, 108, 108, 0.1);
      border-radius: 4px;
      border: 1px solid rgba(245, 108, 108, 0.2);
    }
    
    .fallback-loading {
      font-size: 12px;
      color: #409eff;
      margin-top: 8px;
      padding: 8px;
      background: rgba(64, 158, 255, 0.1);
      border-radius: 4px;
      border: 1px solid rgba(64, 158, 255, 0.2);
    }
    
    .fallback-debug {
      font-size: 11px;
      color: #909399;
      margin-top: 12px;
      padding: 8px;
      background: rgba(144, 147, 153, 0.1);
      border-radius: 4px;
      border: 1px solid rgba(144, 147, 153, 0.2);
      text-align: left;
      
      div {
        margin-bottom: 4px;
        word-break: break-all;
      }
    }
  }
}

.rendered-component {
  width: 100%;
  min-height: 200px;
}

.event-tool-bar{
    height: 35px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    /* border-bottom: 1px solid var(--art-card-border); */
    margin-bottom: 5px;
    border-left: 2px solid #5d87ff;
    background: #5d87ff21;
}
.event-binding-list{

    .event-binding-row{
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 13px;
        background: rgba(0, 0, 0, 0.05);
        padding-left: 8px;
        margin-bottom: 5px;
    }
}



</style>